package com.findme.test.xml;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtil {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     */
    public static String objectToJson(Object data) throws Exception {
        try {
            MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            log.error("对象转json出现异常,异常原因{}", e.getMessage());
            throw new Exception("NotifyResultCode.EBDCPRE004");
        }
    }

    /**
     * 将json结果集转化为对象
     *
     * @param jsonData json数据
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) throws Exception {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            log.error("json转对象出现异常,异常原因{}", e.getMessage());
            throw new Exception("NotifyResultCode.EBDCPRE003");
        }
    }

    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将json数据转换成pojo对象Set
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     */
    public static <T> Set<T> jsonToSet(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(Set.class, beanType);
        try {
            Set<T> set = MAPPER.readValue(jsonData, javaType);
            return set;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     */
    public static <T> Map<String, T> jsonToMap(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory()
                .constructParametricType(LinkedHashMap.class, String.class, beanType);
        try {

            Map<String, T> map = MAPPER.readValue(jsonData, javaType);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
